package org.votes.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.Entity;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.votes.bean.Manager;
import org.votes.service.DetailsService;
import org.votes.service.ManagerService;

@Entity
@Controller
public class ManagerController {
	
	@Autowired
	private ManagerService managerService;
	
	@Autowired
	private DetailsService detailsService;
	
	@RequestMapping("index")
	public String homePage() {
		return "login";
	}

	@RequestMapping(value = "login", method = RequestMethod.POST)
	@ResponseBody  
	public String Login(@RequestParam(value="name", required=true) String name,
						@RequestParam(value="password", required=true) String password,
						Model model) {
		Manager manager = new Manager(name, password);
		boolean flag = managerService.find(manager);
		if(flag)
			return "OK";
		else 
			return "ERROR";
	}
	
	
	@RequestMapping("list")
	public ModelAndView find(HttpServletRequest request, HttpServletResponse response) {
		List<Manager> list = managerService.findAll();
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("list", list);
		return new ModelAndView("result", model);
		
	}
	
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody  
	public ModelAndView addManager(HttpServletRequest request, HttpServletResponse response) {
		String name = request.getParameter("name");
		String password = request.getParameter("password");
		
		Manager manager = new Manager(name, password);
		managerService.save(manager);
		
		return find(request, response);
	}
	
}
